'''
pillow:是python处理图片的模块，很强大
'''
import random

from PIL import Image, ImageDraw, ImageFont


def picture_code():
    def get_char():
        '''通过数字获取ASCII表中的对应字母'''
        return chr(random.randint(65, 90))

    def get_color():
        '''获取随机颜色'''
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    # mode:色系  size：宽高 color：颜色
    # RGB颜色对照表：https://tool.oschina.net/commons?type=3
    img = Image.new(mode='RGB', size=(120, 50), color=(220, 220, 220))

    # 创建画笔对象
    draw = ImageDraw.Draw(img, mode='RGB')

    # 画点 xy：基于图片的坐标，fill:颜色
    for i in range(10):
        draw.point([random.randint(0, 120), random.randint(0, 50)], fill='green')

    # 画线 xy:(起点坐标，终点坐标),width:粗细
    for i in range(5):
        draw.line(
            [random.randint(0, 120), random.randint(0, 50), random.randint(0, 120), random.randint(0, 50)],
            fill='red'
        )

    # 画圆或弧线 start and end:角度
    for i in range(3):
        x = random.randint(0, 120)
        y = random.randint(0, 50)
        x2 = x + 4
        y2 = y + 4
        draw.arc([x, y, x2, y2], start=0, end=90, fill='red')

    # 注意点：.ttf文件路径不能含有中文
    font = ImageFont.truetype(r'.fonts/simsun.ttc', 35)
    char_list = []
    for i in range(5):
        char = get_char()
        char_list.append(char)
        height = random.randint(10, 15)
        draw.text([18 * (i + 1), height], text=char, fill='red', font=font)

    char_code = ''.join(char_list)

    return img, char_code


if __name__ == '__main__':
    img, r = picture_code()
    # 创建在内存中，我们生成在本地
    with open('code.png', 'wb') as f:
        img.save(f, format='png')  # format：格式

    print(r)